#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <arpa/inet.h>
#include <sys/socket.h>
#include <strings.h>
#include <ctype.h>
#include <pthread.h>

// 函数声明
void *send_msg(void *arg);
void *recv_msg(void *arg);

char name[20];
char msg[1024];

int main(int argc, char *argv[]){

    // 参数检查
    if (argc < 4){
        fprintf(stderr, "Usage argc ... \n");
        exit(-1);
    }

    // 输入名字
    sprintf(name, "[%s]", argv[3]);

    // 获取通信文件描述符
    int cfd = socket(PF_INET, SOCK_STREAM, 0);
    if (cfd < 0){
        fprintf(stderr, "socket error ... \n");
        exit(-1);
    }

    // 请求连接
    struct sockaddr_in ser_addr;
    bzero(&ser_addr, sizeof(ser_addr));
    ser_addr.sin_family = AF_INET;
    ser_addr.sin_addr.s_addr = inet_addr(argv[1]);
    ser_addr.sin_port = htons(atoi(argv[2]));
    if(connect(cfd, (struct sockaddr *)&ser_addr, sizeof(ser_addr)) < 0){
        fprintf(stderr, "connect error ... \n");
        exit(-1);
    }

    // 创建子线程---用于接受数据以及发送数据
    pthread_t tid_recv, tid_send;
    pthread_create(&tid_send, NULL, send_msg, (void *)&cfd);
    pthread_create(&tid_recv, NULL, recv_msg, (void *)&cfd);
    // 回收
    pthread_join(tid_send, NULL);
    pthread_join(tid_recv, NULL);

    return 0;
}

void *send_msg(void *arg){
    int cfd = *((int *)arg);
    char info[20 + 1024];
    while (1){
        fgets(msg, sizeof(msg), stdin);
        if (!strcmp(msg, "q\n") || !strcmp(msg, "Q\n")){
            close(cfd);
            exit(0);
        }
        sprintf(info, "%s %s", name, msg);
        write(cfd, info, strlen(info));
    }
    return NULL;
}

void *recv_msg(void *arg){
    int cfd = *((int *)arg);
    char info[20 + 1024];
    int str_len;
    while (1){
        str_len = read(cfd, info, sizeof(info));
        if(str_len < 0){
            return (void *)-1;
        }
        info[str_len] = '\0';
        fputs(info, stdout);
    }
    return NULL;
}